package com.weixing.mall.provider.controller;

import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.base.wrapper.ResultUtil;
import com.weixing.mall.core.annotation.NoNeedAccess;
import com.weixing.mall.base.enums.GenderEnum;
import com.weixing.mall.base.enums.IsEnableEnum;
import com.weixing.mall.core.support.BaseController;
import com.weixing.mall.core.utils.CommonUtil;
import com.weixing.mall.provider.model.domain.RoleUser;
import com.weixing.mall.provider.model.domain.User;
import com.weixing.mall.provider.model.dto.RegisterDto;
import com.weixing.mall.provider.service.IRoleUserService;
import com.weixing.mall.provider.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: kfc
 * @Description: <br/>
 * Date:Create in 2019/9/6 16:56
 * @Modified By:
 */
@Validated
@RestController
@RequestMapping("/sysuser/passport")
@Api(value = "会员注册登录相关Api", tags = "注册登录")
public class SysUserPassportController extends BaseController {

    @Autowired
    private IUserService userService;
    @Autowired
    private IRoleUserService roleUserService;

    @ApiOperation(value = "会员注册")
    @PostMapping("register")
    @NoNeedAccess
    public Result register(@RequestBody RegisterDto registerDto) {

        // 判断手机号是否已注册
        User byMobile = userService.findByMobile(registerDto.getMobile());
        if (null != byMobile) {
            return ResultUtil.error("手机号已被占用");
        }
        // 校验短信验证码
        User user = new User();
        user.setLoginName(registerDto.getMobile());
        user.setIsEnable(IsEnableEnum.ENABLE.getValue());
        user.setMobile(registerDto.getMobile());
        user.setGender(GenderEnum.OTHER.getValue());
        user.setRealName("T" + registerDto.getMobile());
        user.setLoginPwd(CommonUtil.encryptPassword(registerDto.getPassword()));
        user.setDeptId(13L);

        // 保存用户
        userService.save(user);
        // 分配角色
        RoleUser roleUser = new RoleUser();
        roleUser.setUserId(user.getId());
        roleUser.setRoleId(14L);
        roleUserService.save(roleUser);
        return ResultUtil.success();
    }

}
